package com.ruoyi.iot.config;


import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import io.lettuce.core.internal.Exceptions;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

import static feign.FeignException.errorStatus;

/**
 * feign异常拦截器，当从feign抛出异常时走这个对象.
 */
@Configuration
@Slf4j
public class FeignClientErrorDecoder implements ErrorDecoder {

  @Override
  public Exception decode(String methodKey, Response response) {
    String body = null;
    try {
      body = Util.toString(response.body().asReader());
    } catch (IOException e) {
      String error = String.format("feign.IOException:%s",e);
      log.error(error);
    }
    if (response.status() >= 400 && response.status() <= 500) {
      String error = String.format("error status code:%s",response.status());
      throw Exceptions.bubble(new IOException(error));
    }
    return errorStatus(methodKey, response);
  }
}
